// pages/dingdanxiangqing/dingdanxiangqing.js
var utils = require('../../utils/api.js');
var base64 = require('../../utils/base64.js');
var md5 = require('../../utils/md5.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    tipshow: false,
    //../../assets/01.png
    imageUrl: '', //图片地址
    lotteryName: '', //彩种名称
    price: 0, //彩种单价
    totalPrice: 0, //订单总价
    num: 0, //购买数量
    lotteryCode: '', //彩种编码
    payList: [], //请求对象
    // serverSessionKey: 0, //返回serverKey
    timingRotation: 2000, //定时轮询时间
    disabled: false, //连点控制器
    urlReturn: '', //从这个页面访问的
    urlBack: '', //返回
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    var that = this
    that.setData({
      imageUrl: options.imageUrl, //彩种地址
      lotteryName: options.lotteryName, //彩种名称
      price: options.price, //彩种单价
      totalPrice: options.totalPrice, //订单总价
      num: options.num, //购买数量
      lotteryCode: options.lotteryCode, //彩种编号
      urlReturn: options.urlReturn, //来访页面赋值
      urlBack: '/pages/' + options.urlReturn + '/' + options.urlReturn,
    })

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this
    that.setData({ disabled: false })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  },
  queding: function () {
    this.setData({
      tipshow: false
    });
  },
  xiadan: function () {
    //验证必要支付参数 1：给服务发送创建订单
    var that = this
    if (that.data.disabled) {
      wx.showLoading({
        title: '已下单，请等待',
        mask: true,
      })
      setTimeout(function () {
        wx.hideLoading()
      }, that.data.timingRotation)
    }
    wx.showModal({
      title: '提示',
      content: '您确认下单?',
      success: function (res) {
        if (res.confirm) {
          that.setData({ disabled: true })
          that.userGetPayment()
        } else if (res.cancel) {
          return
        }
      }
    })
  },
  /**
   * 创建订单
   */
  userGetPayment: function () {
    var that = this
    // console.log(wx.getStorageSync('serverSessionKey'))
    wx.request({
      url: getApp().globalData.requestUrl + '/createOrder',
      method: "post",
      data: {
        paramList: base64.CusBASE64.encoder('{"machineId":"' + getApp().globalData.machineId + '","lotteryCode":"' + that.data.lotteryCode + '","lotteryName":"' + that.data.lotteryName + '","lotteryCount":"' + that.data.num + '","payType":"' + getApp().globalData.payType + '","totalPrice":"' + that.data.totalPrice + '","price":"' + that.data.price + '","serverSessionKey":"' + wx.getStorageSync('serverSessionKey') + '"}')
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) { //创建订单成功返回
        // console.log(res)
        if (res.statusCode == 200) { //判断wx.request请求是否成功
          if (res.data) {
            var dat = utils.stringToJson(utils.ascii2native(res.data))
            console.log(dat)
            if (dat.status == 0) {
              that.setData({ payList: dat.dataList })
              that.userPutPayment()
            } else {//服务器返回订单失败
              wx.showToast({
                title: '数据错误',
                mask: true,
                duration: 3000,
                icon: 'none',
              })
              return
            }
          } else {//服务器没有返回数据
            wx.showLoading({
              title: '创建订单失败',
              mask: true
            })
            setTimeout(function () {
              wx.hideLoading()
            }, that.data.timingRotation)
            return;
          }
        } else { //创建订单失败
          wx.showLoading({
            title: '创建订单失败',
            mask: true
          })
          setTimeout(function () {
            wx.hideLoading()
          }, that.data.timingRotation)
          return;
        }
      },
      fail: function (res) {
        console.log(res)
      },
      complete: function (res) {
      }
    })
  },
  userPutPayment: function () {
    var that = this
    var stringA = "appId=" + that.data.payList.appid + "&nonceStr=" + that.data.payList.nonceStr + "&package=" + that.data.payList.package + "&signType=MD5&timeStamp=" + that.data.payList.timeStamp + "&key=" + getApp().globalData.apiSecret
    stringA = md5.hexMD5(stringA)
    // console.log(that.data.payList)
    // console.log((stringA))
    // console.log(md5.hexMD5(stringA))
    if (that.data.payList) {
      //发起支付
      wx.requestPayment({
        timeStamp: that.data.payList.timeStamp,
        nonceStr: that.data.payList.nonceStr,
        package: that.data.payList.package,
        signType: that.data.payList.signType,
        paySign: stringA,
        'success': function (res) {
          console.log('支付成功，准备跳转出票界面')
          console.log(res)
          console.log(res.errMsg)
          wx.redirectTo({
            url: '/pages/chupiao/chupiao?orderId=' + that.data.payList.orderId,
          })
          // wx.showToast({
          //   title: '支付成功即将跳',
          //   mask: true
          // })
          // setTimeout(function () {
          // }, 2000)
        },
        'fail': function (res) {
          console.log(res)
          that.setData({ disabled: false })
        },
        'complete': function (res) { }
      })
    } else {//支付失败
    }
  }
})